package com.ruoyi.web.controller.api;


import com.ruoyi.cat.domain.*;
import com.ruoyi.cat.domain.VO.AdGiftVO;
import com.ruoyi.cat.domain.VO.TicketVO;
import com.ruoyi.cat.service.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "api-票卷")
@RestController
@RequestMapping("/api/ticket")
public class TicketController extends BaseController {

    @Autowired
    private IAdTicketClassify2Service adTicketClassify2Service;

    @Autowired
    private IAdTicketClassify1Service adTicketClassify1Service;

    @Autowired
    private IAdTicketRollService adTicketRollService;

    @Autowired
    private IAdTicketLikeService adTicketLikeService;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IAdTicketIprecordService adTicketIprecordService;

    @ApiOperation("获取一级省分类")
    @GetMapping("/getClassify1")
    public AjaxResult getClassify1(AdTicketClassify1 adTicketClassify1)
    {
        List<AdTicketClassify1> list = adTicketClassify1Service.selectAdTicketClassify1List(adTicketClassify1);
        return success(list);
    }

    @GetMapping("/getClassifyData")
    public AjaxResult getClassifyData(AdTicketClassify1 adTicketClassify1)
    {
        List<AdTicketClassify1> list = adTicketClassify1Service.getClassifyData(adTicketClassify1);
        return success(list);
    }

    @ApiOperation("获取二级城市分类")
    @GetMapping("/getClassify2")
    public AjaxResult getClassify2(AdTicketClassify2 adTicketClassify2)
    {
        List<AdTicketClassify2> list = adTicketClassify2Service.selectAdTicketClassify2List(adTicketClassify2);
        return success(list);
    }

    @GetMapping("/getAdGiftClassify2")
    @ApiOperation("获取城市下面最新的十条折扣")
    public AjaxResult getAdGiftClassify2(HttpServletRequest request, AdTicketClassify1 adGift1) {
        AdTicketClassify2 adGiftClassify2 = new AdTicketClassify2();
        adGiftClassify2.setClassifyId(adGift1.getId());
        List<AdTicketClassify2> list2 =  adTicketClassify2Service.selectAdTicketClassify2List(adGiftClassify2);
        list2.forEach(adGiftClassify3->{
            AdTicketRoll adGift = new AdTicketRoll();
            adGift.setCity(adGiftClassify3.getId());
            adGift.setTicketRollTitle(adGift1.getTicketRollTitle());
            adGift.setState("0");
            adGiftClassify3.setAdTicketRollList( adTicketRollService.selectTicketListLimit(adGift));
        });
        return success(list2);
    }

    @GetMapping("/getTicketData")
    @ApiOperation("查询更多折扣信息")
    public TableDataInfo getTicketData(HttpServletRequest request, AdTicketClassify2 adGiftClassify2) {
        AdTicketRoll adGift = new AdTicketRoll();
        adGift.setCity(adGiftClassify2.getId());
        adGift.setState("0");
        adGift.setTicketRollTitle(adGiftClassify2.getTitle());
        startPage();
        List<AdTicketRoll> adGifts = adTicketRollService.selectAdTicketRollList(adGift);
        return getDataTable(adGifts);
    }

    @ApiOperation("api-获取活动详情 如果登录了需要传userId")
    @PostMapping("getAdGiftDetails")
    public AjaxResult getAdGiftDetails(HttpServletRequest request, @RequestBody AdTicketRoll adConfig) {
        AdTicketRoll adGift = adTicketRollService.selectAdTicketRollByIdApp(adConfig.getId(),adConfig.getUserId());
        return success(adGift);
    }

    @ApiOperation("api-分享接口")
    @PostMapping("shareAdGift")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult shareAdGift(HttpServletRequest request, @RequestBody TicketVO adConfig) {
        AdTicketRoll adGift = adTicketRollService.selectAdTicketRollById(adConfig.getTicketId());
        adGift.setForwardNum(adGift.getForwardNum()+1);
        return success(adTicketRollService.updateAdTicketRoll(adGift));
    }

    @ApiOperation("api-喜欢这个活动")
    @PostMapping("likeAdGift")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult likeAdGift(HttpServletRequest request, @RequestBody TicketVO adConfig) {
        String userId = adConfig.getUserId().toString();
        String giftId = adConfig.getTicketId().toString();

        // Redis key
        String likeSetKey = "gift:like:" + giftId;  // 存储点赞用户的集合
        String likeCountKey = "gift:count:" + giftId;  // 存储点赞总数

        // 检查用户是否已经点赞过
        Boolean isLiked = redisTemplate.opsForSet().isMember(likeSetKey, userId);

        AdTicketRoll adGift = adTicketRollService.selectAdTicketRollByIdBy(adConfig.getTicketId());

        if(isLiked != null && isLiked) {
            // 取消喜欢
            redisTemplate.opsForSet().remove(likeSetKey, userId);
            redisTemplate.opsForValue().decrement(likeCountKey);

            // 重新设置过期时间
            redisTemplate.expire(likeSetKey, 1, TimeUnit.HOURS);
            redisTemplate.expire(likeCountKey, 1, TimeUnit.HOURS);

            adGift.setLikeCount(adGift.getLikeCount()-1);

            // 删除数据库记录
            AdTicketLike adGiftLike = new AdTicketLike();
            adGiftLike.setUserId(adConfig.getUserId());
            adGiftLike.setGiftId(adConfig.getTicketId());
            List<AdTicketLike> list = adTicketLikeService.selectAdTicketLikeList(adGiftLike);
            if(list.size() > 0) {
                adTicketLikeService.deleteAdTicketLikeById(list.get(0).getId());
            }
        } else {
            // 新增喜欢
            redisTemplate.opsForSet().add(likeSetKey, userId);
            redisTemplate.opsForValue().increment(likeCountKey);

            // 设置1小时过期时间
            redisTemplate.expire(likeSetKey, 1, TimeUnit.HOURS);
            redisTemplate.expire(likeCountKey, 1, TimeUnit.HOURS);
            adGift.setLikeCount(adGift.getLikeCount()+1);
            // 插入数据库记录
            AdTicketLike adGiftLike = new AdTicketLike();
            adGiftLike.setUserId(adConfig.getUserId());
            adGiftLike.setGiftId(adConfig.getTicketId());
            adTicketLikeService.insertAdTicketLike(adGiftLike);
        }
        return success(adTicketRollService.updateAdTicketRoll(adGift));
    }


    @ApiOperation("api-新增阅读量")
    @PostMapping("addReadCount")
    public AjaxResult addReadCount(HttpServletRequest request, @RequestBody TicketVO ticketVO) {
        String ipAddress = IpUtils.getIpAddr(request);
        Long ticketId = ticketVO.getTicketId();

        log.info("新增阅读量 IP: {}, 活动ID: {}", ipAddress, ticketId);

        // 构建Redis key，格式：gift_ip_today:活动ID:IP:日期
        String today = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date());
        String redisKey = String.format("ticket_ip_today:%s:%s:%s", ticketId, ipAddress, today);

        // 查询活动信息
        AdTicketRoll adGift = adTicketRollService.selectAdTicketRollByIdBy(ticketId);
        if (adGift == null) {
            return error("活动不存在");
        }

        // 使用Redis检查今天是否已访问过
        Boolean hasVisited = redisTemplate.hasKey(redisKey);
        boolean isFirstVisitToday = !hasVisited;

        try {
            // 记录IP访问记录
            AdTicketIprecord adGifiIprecord = new AdTicketIprecord();
            adGifiIprecord.setIpAddress(ipAddress);
            adGifiIprecord.setCreateTime(new Date());
            adGifiIprecord.setIpConfig(ticketId);

            // 如果今天第一次访问，PV设为1；否则增加PV
            if (isFirstVisitToday) {
                adGifiIprecord.setPv(1L);
            } else {
                // 获取当前PV值并增加
                redisTemplate.opsForValue().get(redisKey);
            }

            // 插入或更新IP记录（数据库层面处理唯一约束）
            adTicketIprecordService.insertAdTicketIprecord(adGifiIprecord);

            // 更新活动统计
            // 每次访问都增加总浏览量
            adGift.setQuantity(adGift.getQuantity() + 1);

            // 只有今天第一次访问才增加独立访客数
            if (isFirstVisitToday) {
                adGift.setNumberVisitors(adGift.getNumberVisitors() + 1);
                log.info("IP: {} 今天首次访问活动: {}, 增加独立访客数", ipAddress, ticketId);
            }

            // 更新活动信息
            adTicketRollService.updateAdTicketRoll(adGift);

            // 将访问记录存入Redis，设置过期时间为今天结束
            redisTemplate.opsForValue().set(redisKey, adGifiIprecord.getPv()+"", getSecondsUntilEndOfDay(), TimeUnit.SECONDS);

            log.info("活动: {} 统计更新完成 - 总浏览量: {}, 独立访客: {}, 是否今日首访: {}",
                    ticketId, adGift.getQuantity(), adGift.getNumberVisitors(), isFirstVisitToday);

        } catch (Exception e) {
            log.error("更新阅读量失败 - IP: {}, 活动ID: {}, 错误: {}", ipAddress, ticketId, e.getMessage(), e);
            return error("更新阅读量失败");
        }

        return success(adGift);
    }

    /**
     * 获取到今天结束的剩余秒数
     */
    private long getSecondsUntilEndOfDay() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime endOfDay = now.with(LocalTime.MAX);
        return Duration.between(now, endOfDay).getSeconds();
    }







}
